package com.shenfa.service;

import java.util.HashMap;
import java.util.List;

import net.gmc.util.port.NetServerClient;
import net.gmc.util.port.OperatePort;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.shenfa.bean.NetServer;
import com.shenfa.dao.NetServerDao;
import com.shenfa.util.sequence.SequenceUtil;

/**
 * NetServer参数业务逻辑类
 * 
 * @author yanglong
 *
 */
public class NetServerService {

	private static Logger log = Logger.getLogger(NetServerService.class);
	
	@Autowired
	private NetServerDao netServerDao;
	
	@Autowired
	private SequenceUtil sequenceUtil;
	/**
	 * 根据NetServer参数对象条件查询列表
	 * @param t	NetServer参数对象
	 * @return	NetServer参数列表
	 */
	public List<NetServer> queryList(NetServer t, int start, int limit){
		List<NetServer> list = netServerDao.queryList(t, start, limit);
		if(null == list || list.size() == 0) {
			log.error("list size is 0.");
			return null;
		}
		HashMap<Object, Object> portMap = new HashMap<Object, Object>();
		for(int i = 0; i < list.size(); i++){
			log.debug(list.get(i).getId() + "==" + list.get(i).getPort());
			portMap.put(list.get(i).getId(), list.get(i).getPort());
		}
		try {
			HashMap<Object, Integer> result = NetServerClient.initState(portMap);
			if(result.size() == 0) {
				log.error("init state return size is 0.");
				return null;
			}
			for(int i = 0; i < list.size(); i++) {	//1-已启动，2-停止
				log.debug("return result: " + result.get(list.get(i).getId()));
				list.get(i).setState(String.valueOf(result.get(list.get(i).getId())));
			}
		} catch (Exception e) {
			log.error("set state.", e);
		}
		return list;
	}
	
	/**
	 * 根据KEY启动/停止/重启服务
	 * @param t
	 * @return
	 */
	public String operServer(NetServer t){
		OperatePort op = new OperatePort();
		String result = "0";
		if(t.getState().equals("1")) { //启动
			result = op.netStart(t.getIp(), t.getPort());
		} else if(t.getState().equals("2")) { //停止
			result = op.netStop(t.getIp(), t.getPort());
		} else if(t.getState().equals("3")) { //重启
			result = op.netReset(t.getIp(), t.getPort());
		}
		return result;
	}
	
	public int queryCount(NetServer t){
		return netServerDao.queryCount(t);
	}
	
	/**
	 * 添加NetServer参数信息
	 * @param t	NetServer参数对象
	 * @return	1成功，0失败
	 */
	public int add(NetServer t){
		t.setId(Integer.parseInt(sequenceUtil.getSequence(SequenceUtil.SEQ_NETSERVER_PARA)));
		return netServerDao.add(t);
	}
	
	/**
	 * 修改NetServer参数信息
	 * @param t	NetServer参数对象
	 * @return	1成功，0失败
	 */
	public int upd(NetServer t){
		return netServerDao.upd(t);
	}
	
	/**
	 * 删除NetServer参数信息
	 * @param t	NetServer参数对象
	 * @return	1成功，0失败
	 */
	public int del(NetServer t){
		return netServerDao.del(t);
	}
	
}
